package org.cncy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;

import java.io.Serializable;

/**
 * 设备管理器激活后，上报状态
 */
public class I3009JavaSampler extends AbstractJavaSamplerClient implements Serializable {

    private static Logger log = LoggerFactory.getLogger(I3009JavaSampler.class);
    private static final long serialVersionUID = 240L;
    private static final String URL = "url";

    public I3009JavaSampler() {
        log.debug(Utils.whoAmI(this) + "\tConstruct");
    }


    @Override
    public Arguments getDefaultParameters() {
        Arguments arguments = new Arguments();
        arguments.setComment("设备激活接口");
        arguments.addArgument(URL, "");
        arguments.addArgument("ClientUID", "");
        arguments.addArgument("TenantID", "");
        arguments.addArgument("userName", "");
        return arguments;
    }

    public SampleResult runTest(JavaSamplerContext javaSamplerContext) {

        SampleResult results = new SampleResult();
        //返回请求值，体现在jmeter查看结果数请求里面
        String ClientUID = javaSamplerContext.getParameter("ClientUID");
        String url = javaSamplerContext.getParameter(URL);
        String tenantID = javaSamplerContext.getParameter("TenantID");
        String userName = javaSamplerContext.getParameter("userName");
        String body = "<?xml version='1.0' encoding='UTF-8' ?><Request><OperID><TenantID>" + tenantID + "</TenantID><ClientUID>" + ClientUID + "</ClientUID><FlowNum></FlowNum><Timezone>-1</Timezone><Result>-1</Result><ClientVersion>2.0.1</ClientVersion><ClientBuildNum>200001</ClientBuildNum></OperID><ClientIDInfo><UserName>" + userName + "</UserName></ClientIDInfo></Request>";
        log.debug(body);
        results.setSamplerData("请求地址 : " + url);
        results.setSamplerData(body);

        results.sampleStart();
        try {
            byte[] bytes = HttpsUtils.doPost(url, HttpsXMLUtil.getXMLRequestByte(3009, body));
            // byte[] bytes1 = Utils.interceptBody(bytes);
            results.setSuccessful(true);//这里决定测试用例成功还是失败
            //设置返回信息
            results.setResponseCode("200");
            results.setResponseMessage("成功测试");
            //results.setSampleLabel("设备激活");
            //返回结果
            results.setResponseData(new String(Utils.interceptBody(bytes)), "utf-8");
        } catch (Exception e) {
            log.error(e.getMessage());
            results.setSuccessful(false);
        } finally {
            // Record end time and populate the results.
            results.sampleEnd();
        }
        if (log.isDebugEnabled()) {
            log.debug(Utils.whoAmI(this) + "\tTime:\t" + results.getTime());
        }

        return results;
    }
}
